package problem290;

import java.util.HashMap;

//290.单词规律
//https://leetcode.cn/problems/word-pattern/?envType=study-plan-v2&envId=top-interview-150

class Solution {
    public boolean wordPattern(String pattern, String s) {
        String[] words = s.split(" ");
        int n = words.length;
        if(n != pattern.length()) return false;
        HashMap<Character, String> hash1 = new HashMap<>();
        HashMap<String, Character> hash2 = new HashMap<>();
        for(int i = 0; i<n; i++) {
            char ch = pattern.charAt(i);
            String word = words[i];
            if(!hash1.containsKey(ch)) {
                if(hash2.containsKey(word) && hash2.get(word) != ch) return false;
                hash1.put(ch, word);
                hash2.put(word, ch);
            }else {
                if(!hash1.get(ch).equals(word)) return false;
            }
        }
        return true;
    }
}